<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\AssignCouponCard;
use App\Admin\Extensions\AssignCouponCardToSecondAgent;
use App\Models\Admin;
use App\Models\Agent;
use App\Models\CouponCardAssignLog;
use App\Models\CouponCardCreateLog;
use App\Models\Role;
use App\Http\Controllers\Controller;
use App\Models\CouponCard;
use App\Repositories\AgentRepository;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Encore\Admin\Auth\Permission;

class AgentController extends Controller
{
    use HasResourceActions;

    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            $admin = \Admin::user();
            if ($admin && $admin->isAgentLevelTwo()) {
                //二级代理只能编辑自己
                $currentRouteName = \Route::currentRouteName();
                $id = \Route::current()->parameter('vendor');
                logger(sprintf('user: %s, currentRouteName: %s, id: %s', $admin->name, $currentRouteName, $id));
                if (!in_array($currentRouteName, ['admin.vendor.edit', 'admin.vendor.update'])) {
                    Permission::error();
                }
                if ($id != $admin->agent->id) {
                    Permission::error();
                }
            }
            return $next($request);
        });

    }

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('代理商')
            ->description('列表')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('Detail')
            ->description('description')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('Edit')
            ->description('description')
            ->body($this->form($id)->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('Create')
            ->description('description')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Agent);
        //根据权限过滤列表
        $isSuperAdmin = \Admin::user()->isSuperAdmin();
        $isOfficial = \Admin::user()->isOfficial();
        $isAgentLevelOne = \Admin::user()->isAgentLevelOne();
        $isAgentLevelTwo = \Admin::user()->isAgentLevelTwo();

        $where_filter_pid = 0;
        if(!$isSuperAdmin && !$isOfficial && $isAgentLevelOne) $where_filter_pid = \Admin::user()->agent()->first()->id;

        $grid->model()->with(['admin'])
            ->when($where_filter_pid,function ($query) use ($where_filter_pid){return $query->where("parent_id","=",$where_filter_pid);})
            ->orderBy('id', 'desc');

        $grid->id('ID');
        $grid->name('代理商名称');
        $grid->column('admin.username', '账号用户名');
        $grid->column('admin.id', '账号ID');
        $grid->remarks('备注');

        $grid->created_at('创建时间');

        $grid->actions(function ($actions) use($isSuperAdmin,$isOfficial,$isAgentLevelOne,$where_filter_pid) {
            if(!$isSuperAdmin && !$isOfficial && $isAgentLevelOne)
            {
                $actions->append(new AssignCouponCardToSecondAgent($actions->getKey()));
            }
            elseif ($isSuperAdmin || $isOfficial)
            {
                //如果是超级admin或者官方人员 对一级代理商添加分发按钮 二级的不加
                $cur_agent_id = $actions->getKey();
                $cur_agent_admin_uid = Agent::find($cur_agent_id) ? Agent::find($cur_agent_id)->admin_uid : "";
                if(!empty($cur_agent_admin_uid))
                {
                    $isSuperAdmin = Admin::find($cur_agent_admin_uid)->isSuperAdmin();
                    $isOfficial = Admin::find($cur_agent_admin_uid)->isOfficial();
                    $isAgentLevelOne = Admin::find($cur_agent_admin_uid)->isAgentLevelOne();
                    if(!$isSuperAdmin && !$isOfficial && $isAgentLevelOne) $actions->append(new AssignCouponCard($actions->getKey()));
                }
            }
        });
        return $grid;
    }

    /**
     * @desc 官方或者超级管理员 优惠券分发 给一级代理商
     * @param Request $request
     * @return array|mixed
     */
    public function assignCouponCard(Request $request)
    {
        set_time_limit(0);
        $create_card_start = $request->create_card_start;
        $create_card_end = $request->create_card_end;
        $int_create_card_start = (int)$request->create_card_start;
        $int_create_card_end = (int)$request->create_card_end;
        $agent_id = (int)$request->id;
        if(!$agent_id) return api(-1,'请传入代理商id',[]);
        try
        {
            $agent_data = Agent::findOrFail($agent_id);
        }
        catch (\Exception $exception)
        {
            return api("代理商id参数错误，请刷新页面重试");
        }
        list($ret,$message) = CouponCard::checkValidCardNo($create_card_start,$create_card_end,$agent_id);
        if(!$ret) return api($message);
        $update = CouponCard::whereBetween("coupon_card_no",[$create_card_start,$create_card_end])->update([
            'first_class_agent_id'=>$agent_id,
//            'assign_admin_uid'=>\Admin::user()->id,
//            'assign_admin_at'=>date('Y-m-d H:i:s')
        ]);
        if($update)
        {
            $card_assign_log_insert_all_list = [];
            for ($i=$int_create_card_start;$i<=$int_create_card_end;$i++)
            {
                $card_assign_log_insert_all_list[] = [
                    'card_no'=>str_pad($i,13,0,STR_PAD_LEFT),
                    'assign_admin_uid'=>\Admin::user()->id,
                    'assign_admin_at'=>date('Y-m-d H:i:s'),
                    'remark'=>"官方人员给一级代理商分配优惠卡券",
                    'created_at'=>date('Y-m-d H:i:s'),
                    'updated_at'=>date('Y-m-d H:i:s'),
                ];
            }
            CouponCardAssignLog::insert($card_assign_log_insert_all_list);
            return api(RET_OK,RET_SUCCESS_MSG,[]);
        }
        else return api("分配错误");
    }

    /**
     * @desc 一级代理商给二级代理商分配
     * @param Request $request
     */
    public function assignCouponCardSecond(Request $request)
    {
        set_time_limit(0);
        $create_card_start = $request->create_card_start;
        $create_card_end = $request->create_card_end;
        $int_create_card_start = (int)$request->create_card_start;
        $int_create_card_end = (int)$request->create_card_end;
        $agent_id = (int)$request->id;
        if(!$agent_id) return api(-1,'请传入代理商id',[]);
        try
        {
            $agent_data = Agent::findOrFail($agent_id);
        }
        catch (\Exception $exception)
        {
            return api("代理商id参数错误，请刷新页面重试");
        }
        list($ret,$message) = CouponCard::checkValidCardNoAgent($create_card_start,$create_card_end,$agent_id);
        if(!$ret) return api($message);
        $update = CouponCard::whereBetween("coupon_card_no",[$create_card_start,$create_card_end])->update([
            'second_class_agent_id'=>$agent_id,
//            'assign_admin_uid'=>\Admin::user()->id,
//            'assign_admin_at'=>date('Y-m-d H:i:s')
        ]);
        if($update)
        {
            $card_assign_log_insert_all_list = [];
            for ($i=$int_create_card_start;$i<=$int_create_card_end;$i++)
            {
                $card_assign_log_insert_all_list[] = [
                    'card_no'=>str_pad($i,13,0,STR_PAD_LEFT),
                    'assign_admin_uid'=>\Admin::user()->id,
                    'assign_admin_at'=>date('Y-m-d H:i:s'),
                    'remark'=>"一级代理商给二级代理商分配优惠卡券",
                    'created_at'=>date('Y-m-d H:i:s'),
                    'updated_at'=>date('Y-m-d H:i:s'),
                ];
            }
            CouponCardAssignLog::insert($card_assign_log_insert_all_list);
            return api(RET_OK,RET_SUCCESS_MSG,[]);
        }
        else return api("分配错误");

    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Agent::findOrFail($id));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($id = null)
    {
        $form = new Form(new Agent);

        $form->text('admin.name', '账号名称')->placeholder('如：张三')->rules('required');
        $form->text('admin.username', '账号登录名')->placeholder('如：zhangsan')->rules(['required']);
        $form->password('admin.password', '账号登录密码')->placeholder('如：123456')->rules(['required']);

        if (\Admin::user()->isOfficial())
        {
            //官方人员，添加时可以指定一级代理商
            $form->select('parent_id', '上级代理商')->options(Agent::where('level', 1)->where("id", "!=", $id)->pluck('name', 'id'));
        } else {
            $form->hidden('parent_id', '上级代理商')->value(0);
        }
        $form->hidden('level', '层级');
        $form->text('name', '代理商名称')->placeholder('如：XXX餐饮有限公司')->rules(['required']);
        $form->number('commission_percent')->placeholder('佣金比例，0~100')->rules(['integer', 'between:0,100']);
        $form->text('remarks', '备注');

        $logPrefix = __METHOD__;
        $form->saving(function (Form $form) use ($id, $logPrefix) {
//            dd($form, $form->admin, $form->model()->admin);
            if ($form->admin['password'] && optional($form->model()->admin)->password != $form->admin['password']) {
                logger(sprintf("%s, input password: %s, model password: %s", $logPrefix, $form->admin['password'], optional($form->model()->admin)->password));
                $inputAdmin = $form->admin;
                $inputAdmin['password'] = bcrypt($inputAdmin['password']);
                $form->admin = $inputAdmin;
            }
            if ($form->parent_id) {
                //指定了上级，它肯定是二级
                $form->level = 2;
            } else {
                if (\Admin::user()->isAgentLevelOne()) {
                    //一级代理商创建的，自动自己是他的上级，自然新建的是二级
                    $form->parent_id = \Admin::user()->agent->id;
                    $form->level = 2;
                } else {
                    $form->parent_id = 0;
                    $form->level = 1;
                }
            }
        });

        $form->saved(function ($form) use ($id, $logPrefix) {
            if (\Route::currentRouteName() != 'admin.vendor.store') {
                if (\Admin::user()->isAgentLevelTwo()) {
                    admin_toastr('保存成功');
                    return back();// 二级代理商编辑个人信息，不能跳转列表
                } else {
                    return;
                }
            }
            //创建之后，用户会自动创建，需要关联一个角色
            $log = sprintf("%s, new agent: %s, assign role to admin_user: %s", $logPrefix, $form->model()->id, $form->model()->admin_uid);
            if ($form->model()->level == 1)
            {
                //为一级代理。
                logger("$log, level 1, role: " . Role::SLUG_AGENT_LEVEL_1);
                $roles = Role::whereIn("slug", [Role::SLUG_AGENT, Role::SLUG_AGENT_LEVEL_1])->get();
            }
            else
            {
                logger("$log, level 2, role: " . Role::SLUG_AGENT_LEVEL_2);
                $roles = Role::whereIn("slug", [Role::SLUG_AGENT, Role::SLUG_AGENT_LEVEL_2])->get();
            }
            $form->model()->admin()->firstOrFail()->roles()->saveMany($roles);
            if (\Admin::user()->isAgentLevelTwo()) {
                admin_toastr('保存成功');
                return back();// 二级代理商编辑个人信息，不能跳转列表
            }

        });

        return $form;
    }

    /*
    public function store(Request $request)
    {
        if ($validationMessages = $this->form()->validationMessages($request->all())) {
            return back()->withInput()->withErrors($validationMessages);
        }
        dd($request);
        //先将图片上传
        $uploadFiles = $request->file();
        if ($uploadFiles)
        {
            foreach ($uploadFiles as $field => $img)
            {
                $keys = [];
                foreach (array_wrap($img) as $_img)
                {
                    $uploadResult = $_img->store(config('admin.upload.directory.image'));
                    if ($uploadResult)
                    {
                        $keys[] = $uploadResult;
                    }
                }
                $keyStored = is_array($img) ? $keys : $keys[0];
                $request->request->remove($field);
                $request->request->add([$field => $keyStored]);
            }

        }
        $agent = (new AgentRepository())->createAgent($request);

        admin_toastr('创建成功');

        return redirect()->route('vendor.index');
    }

    public function update(Request $request)
    {
        if ($validationMessages = $this->form()->validationMessages($request->all())) {
            return back()->withInput()->withErrors($validationMessages);
        }
        dd($request);
        //先将图片上传
        $uploadFiles = $request->file();
        if ($uploadFiles)
        {
            foreach ($uploadFiles as $field => $img)
            {
                $keys = [];
                foreach (array_wrap($img) as $_img)
                {
                    $uploadResult = $_img->store(config('admin.upload.directory.image'));
                    if ($uploadResult)
                    {
                        $keys[] = $uploadResult;
                    }
                }
                $keyStored = is_array($img) ? $keys : $keys[0];
                $request->request->remove($field);
                $request->request->add([$field => $keyStored]);
            }

        }
        $agent = (new AgentRepository())->createAgent($request);

        admin_toastr('创建成功');

        return redirect()->route('vendor.index');
    }
    */
}
